import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, message, Modal, Radio, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {isSuccess} from "@/utils/utils";
import {OpCircleManager} from "@/services/api-functions";
// @ts-ignore
import {history} from "umi";


export const circleDelete = async (select: any) => {
  if (!select) return false;
  try {
    if (isSuccess((await OpCircleManager.del(select.id))?.code)) {
      message.success('删除成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

export const changeCircleState = async (select: any, state: 'OPEN'|'DISABLE') => {
  if (!select) return false;
  try {
    if (isSuccess((await OpCircleManager.operate(select.id, state))?.code)) {
      message.success('删除成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

export interface ResourceListProps {
  type: 'SIMPLE'|'COURSE'
}

const CircleList: React.FC<ResourceListProps> = ({type}) => {

  const [useStatus, setUseStatus] = useState<'ALL' | 'OPEN' | 'DISABLE'>('ALL');
  const [countInfo, setCountInfo] = useState<{ ALL: number, OPEN: number, DISABLE: number }>({
    ALL: 0,
    OPEN: 0,
    DISABLE: 0,
  });

  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: '圈子标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 220,
      fixed: 'left'
    },
    {
      title: '圈主',
      dataIndex: ['circleBelongUserDto', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '圈子简介',
      dataIndex: 'introduce',
      ellipsis: true,
      hideInSearch: true,
      width: 370,
    },
    {
      title: '圈友数',
      dataIndex: 'userNum',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '主题动态数',
      dataIndex: 'themeNum',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '精选动态数',
      dataIndex: 'essenceNum',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '关联课程',
      dataIndex: 'courseDto',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
      render: (_, record) => record.courseDto ? <a href={`/course/detail/${record.courseDto?.courseId}`}>{record.courseDto?.title}</a> : '-'
    },
    {
      title: '最近活跃时间',
      dataIndex: 'lastThemeTime',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '圈主',
      dataIndex: 'userName',
      ellipsis: true,
      hideInTable: true,
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreateTimeRange',
      valueType: 'dateTimeRange',
      width: 170,
      hideInTable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      width: 270,
      fixed:'right',
      render: (_, record) => [
        // <a key="edit" href={`/resource/detail/${record?.id}`}>详情</a>,
        <a key="edit" onClick={()=>history.push(`/circle/edit/${record.id}`)}>编辑</a>,
        <a key="edit"
           onClick={() => Modal.confirm({
             title: '提示',
             icon: <ExclamationCircleOutlined/>,
             content: <span>确定要删除 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
             okText: '删除',
             cancelText: '取消',
             onOk: async () => {
               if (await circleDelete(record)) {
                 actionRef.current?.reload()
               }
             },
           })}
        >删除</a>,
        record.state !== 'DISABLE'
          ? <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要禁用 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
            okText: '禁用',
            cancelText: '取消',
            onOk: async () => {
              if (await changeCircleState(record, 'DISABLE')) {
                actionRef.current?.reload()
              }
            },
          })}>禁用</a>
          : <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要启用荐 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
            okText: '启用',
            cancelText: '取消',
            onOk: async () => {
              if (await changeCircleState(record, 'OPEN')) {
                actionRef.current?.reload()
              }
            },
          })}>启用</a>,
        <a key="edit" onClick={()=>history.push(`/circle/post/list?circleId=${record.id}`)}>查看动态</a>,
      ],
    },
  ];
  return (
    <>
      <ProTable<any, any>
        actionRef={actionRef}
        rowKey="key"
        search={{labelWidth: 120,}}
        headerTitle={<Radio.Group value={useStatus} onChange={(e) => {
          setUseStatus(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.ALL ?? 0}</Radio.Button>
          <Radio.Button value='OPEN'>启用中 {countInfo?.OPEN ?? 0}</Radio.Button>
          <Radio.Button value='DISABLE'>已禁用 {countInfo?.DISABLE ?? 0}</Radio.Button>
        </Radio.Group>}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => history.push('/circle/edit')}>
            <PlusOutlined/> 新建
          </Button>,
          <Button onClick={() => history.push('/circle/post/list')}>动态列表</Button>,
        ]}
        request={async (params) => {

          const query = {...params, circleType: type}

          if (params.gmtCreateTimeRange) {
            query.gmtCreateStart = params.gmtCreateTimeRange[0]
            query.gmtCreateEnd = params.gmtCreateTimeRange[1]
            delete query.gmtCreateTimeRange
          }
          if (useStatus !== 'ALL') {
            query.state = useStatus
          }

          const res = await OpCircleManager.circleCount(type);

          if(isSuccess(res.code)){
            setCountInfo(res.data)
          }

          const {data: {data, total}, code}: any = await OpCircleManager.pageQuery(query);

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />
    </>
  );
};

export default CircleList;
